package club.gskj.gulimall.product.app;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import club.gskj.gulimall.product.entity.CategoryEntity;
import club.gskj.gulimall.product.service.CategoryService;
import club.gskj.common.utils.R;


/**
 * 商品三级分类
 *
 * @author 康纳-connor
 * @email 2417039231@gmail.com
 * @date 2020-12-27 15:07:43
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有分类、子分类。以树形结构封装返回
     */
    @RequestMapping("/list/tree")
    public R list() {
        // 返回树形结构 分类列表
        List<CategoryEntity> list = categoryService.listWithTree();


        return R.ok().put("data", list);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId) {
        CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("data", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category) {
        categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改单个分类
     */
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category) {
//        categoryService.updateById(category);

        /* 级联更新中间表中相关联的字段信息，保持数据一致性*/
        categoryService.updateCascade(category);
        return R.ok();
    }

    /***
     *  批量修改多条数据
     * @param categoryEntities
     * @return R
     */
    @RequestMapping("/updates/sort")
    public R updates(@RequestBody CategoryEntity[] categoryEntities) {
        // 修改多条数据
        categoryService.updateBatchById(Arrays.asList(categoryEntities));
        return R.ok();
    }


    /**
     * 删除
     *
     * @RequestBody:获取请求体,必须发送post请求. SpringMVC自动将请求体的数据(json), 转为方法参数中对应的对象
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds) {
        //  1.检查当前删除的菜单,是否被别的地方引用.
        categoryService.removeMenuByIds(Arrays.asList(catIds));
        return R.ok();
    }
}
